import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../store/user';
import { onMounted } from 'vue';
import path from 'path';

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { roles: ['超级管理员'] }, // 只有超级管理员可以访问
    children: [
      {
        path: 'course_choose',
        name: 'CourseChoose',
        component: () => import('../views/CourseChoose.vue'),
        meta: {
          roleId: 1
        }
      },
      {
        path: 'leave_submit',
        name: 'LeaveSubmit',
        component: () => import('../views/LeaveSubmit.vue'),
        meta: {
          roleId: 1
        }
      },
      {
        path: 'review_by_head_teacher',
        name: 'ReviewByHeadTeacher',
        component: () => import('../views/ReviewByHeadTeacher.vue'),
        meta: {
          roleId: 2
        }
      },
      {
        path: 'review_by_counselor',
        name: 'ReviewByCounselor',
        component: () => import('../views/ReviewByCounselor.vue'),
        meta: {
          roleId: 3
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },

  // 其他路由
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// onMounted(() => {
//   if (localStorage.getItem('activeMenu')) localStorage.removeItem('activeMenu')
// })


// 在路由守卫中处理重定向逻辑
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const userRoleId = userStore.user?.roleId;

  if (!userRoleId) {
    if (to.path !== '/login') {
      next({ name: 'Login' }); // 未登录且访问非登录页面则重定向
    } else {
      next(); // 如果访问的是登录页，允许进入
    }
  } else if (to.meta.roleId && to.meta.roleId != userRoleId) {
    next({ name: 'Home' })
    // localStorage.removeItem('activeMenu'); // 清除激活状态
  } else if (to.meta.roleId && to.meta.roleId == userRoleId && to.path == '/home') {
    localStorage.removeItem('activeMenu')
    // 如果用户已登录，判断角色权限
    if (userRoleId === 1) {
      next({ name: "CourseChoose" });
      localStorage.setItem('activeMenu', '1-1'); // 修改激活状态
    }
    if (userRoleId === 2) {
      localStorage.setItem('activeMenu', '1-3'); // 修改激活状态
      next({ name: "ReviewByHeadTeacher" });
    }
    if (userRoleId === 3) {
      localStorage.setItem('activeMenu', '1-4'); // 修改激活状态
      next({ name: "ReviewByCounselor" });
    }

  }
  else {
    next(); // 允许访问
  }


});

export default router;
